<template>
  <div class="model-container">
    <div class="model-content">
      <!-- 文件上传部分 -->
      <div class="upload-section">
        <h2 class="section-title">Upload Model File</h2>
        <el-upload 
          ref="upload" 
          class="upload-demo" 
          action="http://localhost:3456/api/upload" 
          :limit="1"
          :on-exceed="handleExceed" 
          :before-upload="beforeUpload" 
          :on-success="handleSuccess" 
          :on-error="handleError"
          :on-remove="handleRemove"
          name="file" 
          accept=".csv" 
          :auto-upload="true" 
          :disabled="!selectedTopology">
          <template #trigger>
            <button class="neu-button" :disabled="!selectedTopology">Select CSV File</button>
          </template>
          <template #tip>
            <div class="upload-tip">
              {{ selectedTopology ? 'Please upload a CSV file containing the flow matrix data.' : 'Please select a topology first.' }}
              <br>
              {{ selectedTopology ? 'Rows represent time steps, columns represent node pairs.' : '' }}
            </div>
          </template>
        </el-upload>
      </div>

      <!-- 选择拓扑图展示部分 -->
      <div class="topology-section">
        <h2 class="section-title">Select Topology</h2>
        <el-select v-model="value" placeholder="Select Topology" class="topology-select" @change="handleSelectChange">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>

      <!-- 条件渲染拓扑图 -->
      <div v-if="selectedTopology" class="topology-display">
        <component :is="selectedTopology" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import TopologyGraph1 from '@/views/Model/components/TopologyGraph1.vue'
import TopologyGraph2 from '@/views/Model/components/TopologyGraph2.vue'

const upload = ref()
const value = ref('')
const selectedTopology = ref(null)
const uploadedFile = ref(null)

// 只保留两个选项
const options = [
  { value: 'topology1', label: 'USA Network' },
  { value: 'topology2', label: 'Topology Graph 2' }
]

// 拓扑图路径与选项的映射
const topologyMap = {
  topology1: TopologyGraph1,
  topology2: TopologyGraph2
}

const handleExceed = (files) => {
  ElMessage.warning('Only one file can be uploaded at a time')
  upload.value.clearFiles()
  const file = files[0]
  upload.value.handleStart(file)
}

const beforeUpload = (file) => {
  const isCSV = file.type === 'text/csv' || file.name.toLowerCase().endsWith('.csv')
  if (!isCSV) {
    ElMessage.error('Please upload a CSV file!')
    return false
  }

  // 修改文件大小限制为100MB
  const isLt100M = file.size / 1024 / 1024 < 100
  if (!isLt100M) {
    ElMessage.error('File size must be less than 100MB!')
    return false
  }

  return true
}

const handleSuccess = async (response, uploadFile) => {
  try {
    uploadedFile.value = response.filename
    
    // 如果选择了USA Network，设置特定参数
    if (value.value === 'topology1') {
      await fetch('http://localhost:3456/api/set-params', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          dataset_name: 'abilene',
          rm_fn: `upload/${response.filename}`
        })
      });
    }
    ElMessage.success('File uploaded successfully');
  } catch (error) {
    console.error('Failed to set parameters:', error);
    ElMessage.error('Failed to set parameters');
  }
}

const handleError = (error) => {
  console.error('Upload error:', error)
  let errorMessage = 'Failed to upload file'
  if (error.response && error.response.data) {
    errorMessage = error.response.data.message || errorMessage
  }
  ElMessage.error(errorMessage)
}

const handleRemove = () => {
  uploadedFile.value = null
}

const handleSelectChange = (val) => {
  selectedTopology.value = topologyMap[val]
  // 清除已上传的文件
  if (upload.value) {
    upload.value.clearFiles()
  }
  uploadedFile.value = null
}
</script>

<style lang="scss" scoped>
.model-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ecf0f3;
  padding: 20px;
}

.model-content {
  width: 1000px;
  min-height: 600px;
  background-color: #ecf0f3;
  border-radius: 12px;
  padding: 25px;
  box-shadow:
    10px 10px 10px #d1d9e6,
    -10px -10px 10px #f9f9f9;
}

.section-title {
  font-size: 24px;
  font-weight: 700;
  color: #181818;
  margin-bottom: 20px;
}

.upload-section,
.topology-section {
  margin-bottom: 30px;
}

.neu-button {
  width: 180px;
  height: 50px;
  border-radius: 25px;
  margin: 10px;
  font-weight: 700;
  font-size: 14px;
  letter-spacing: 1.15px;
  background-color: #4B70E2;
  color: #f9f9f9;
  box-shadow:
    8px 8px 16px #d1d9e6,
    -8px -8px 16px #f9f9f9;
  border: none;
  outline: none;
  cursor: pointer;

  &:hover {
    box-shadow:
      6px 6px 10px #d1d9e6,
      -6px -6px 10px #f9f9f9;
    transform: scale(0.985);
    transition: 0.25s;
  }

  &:disabled {
    background-color: #a0a5a8;
    cursor: not-allowed;
  }
}

.upload-tip {
  color: #a0a5a8;
  font-size: 14px;
  margin-top: 10px;
}

.topology-select {
  width: 300px;

  :deep(.el-input__wrapper) {
    background-color: #ecf0f3;
    box-shadow:
      inset 2px 2px 4px #d1d9e6,
      inset -2px -2px 4px #f9f9f9;
    border-radius: 8px;
  }
}

.topology-display {
  margin-top: 30px;
  padding: 20px;
  background-color: #ecf0f3;
  border-radius: 12px;
  box-shadow:
    inset 2px 2px 4px #d1d9e6,
    inset -2px -2px 4px #f9f9f9;
}
</style>